package com.example.shixun.controller;

import com.example.shixun.pojo.PostReply;
import com.example.shixun.pojo.PostReplyDTO;
import com.example.shixun.pojo.Result;
import com.example.shixun.pojo.User;
import com.example.shixun.service.PostRlyService;
import com.example.shixun.service.PostService;
import com.example.shixun.service.UserService;
import com.example.shixun.utils.GetIdByToken;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/postRly")
public class PostRlyController {
    @Autowired
    PostRlyService postRlyService;
    @Autowired
    PostService postService;
    @Autowired
    UserService userService;
    @Autowired
    GetIdByToken getIdByToken;
    @ApiOperation("根据postId查找回帖")
    @GetMapping("/findRlyByPostId")
    public Result findRlyById(@RequestParam("id")Integer id){
        List<PostReply> postReplyList=postRlyService.findByPostId(id);
        List<PostReplyDTO> resLists=new ArrayList<>();
        for(PostReply postReply:postReplyList){
            PostReplyDTO dto=new PostReplyDTO();
            dto.setId(postReply.getId());
            dto.setUserId(postReply.getUserId());
            dto.setPostId(postReply.getPostId());
            dto.setContent(postReply.getContent());
            User user= (User) userService.getUserById(dto.getUserId()).getData();
            if(user!=null){
                dto.setUserName(user.getName());
                dto.setUserAvatar(user.getAvatar());
                resLists.add(dto);
            }
        }
        return Result.success(resLists);
    }
    @ApiOperation("回帖")
    @PostMapping("/rlyPost")
    public Result replyPost(@RequestBody PostReply postReply,
                            @RequestHeader("token")String token){
        postReply.setUserId(getIdByToken.getIdByToken(token));
        postService.addReplies(postReply.getPostId());
        return Result.success(postRlyService.save(postReply));
    }
}
